<?php

class Quad_Ini {
	
	protected static $_parsed = array();
	
	public static function get($name, $iniPath = null) {
		if (!isset(self::$_parsed[$name])) {
			if (!is_file($iniPath)) {
				throw new Quad_Exception("Ini file `$iniPath` not found.");
			}
			$ini = parse_ini_file($iniPath, true);
			if ($ini === false) {
				throw new Quad_Exception("Error parsing `$iniPath` as an ini file.");
			}
			self::$_parsed[$name] = new self($ini);
		}
		return self::$_parsed[$name];
	}
	
	protected function __construct($iniArray) {
		$this->_rawArray = $iniArray;
		foreach ($iniArray as $section => $values) {
			$sectionObject = new stdClass;
			foreach ($values as $key => $value) {
				self::_addProperty($key, $value, $sectionObject);
			}
			$this->$section = $sectionObject;
		}
	}
	
	protected static function _addProperty($key, $value, $parent) {
		if (strpos($key,'.') === false) {
			$parent->$key = $value;
		}
		else {
			$parts = explode('.',$key);
			$section = array_shift($parts);
			$newKey = join('.',$parts);
			if (!isset($parent->$section)) {
				$parent->$section = new stdClass;
			}
			self::_addProperty($newKey, $value, $parent->$section);
		}
	}
	
}